#include "listwidget.h"

ListView::ListView(QWidget *parent):QListView(parent)
{
    setAttribute(Qt::WA_StyledBackground, true);

    QScroller* scroller = QScroller::scroller(this);
    QScrollerProperties properties = scroller->scrollerProperties();
    properties.setScrollMetric(QScrollerProperties::VerticalOvershootPolicy, QScrollerProperties::OvershootAlwaysOff);//关闭越区
    scroller->setScrollerProperties(properties);
    connect(scroller, &QScroller::stateChanged, this, &ListView::stateChanged);

    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setDragEnabled(false);
    setWordWrap(true);
    setWrapping(false);
    setVerticalScrollMode(ListView::ScrollPerPixel);
    setFrameShape(ListView::NoFrame);
    setResizeMode(ListView::Adjust);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setFocusPolicy(Qt::NoFocus);
    setViewMode(ListView::ListMode);
    setFlow(ListView::TopToBottom);
    QScroller::grabGesture(this, QScroller::TouchGesture);
    connect(this, &ListView::pressed, this, [&]
    {
        //WELOG_DEBUG() << "pressed";
        timer->start();
        isLongPress = false;
        itemPress = true;
    });

    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [&]
    {
        isLongPress = true;
        emit longPress();
    });
    timer->setInterval(1500);

    connect(this, &QListView::clicked, this, &ListView::clicked);
}

void ListView::mousePressEvent(QMouseEvent *e)
{
    isPress = true;
    pressPos = e->pos();

    QListView::mousePressEvent(e);
}

void ListView::mouseMoveEvent(QMouseEvent *e)
{
    if(isPress)
    {
        if((e->pos().x() - pressPos.x() > 10) || (e->pos().y() - pressPos.y() > 10) || \
            e->pos().x() - pressPos.x() < -10 || (e->pos().y() - pressPos.y() < -10))
        {
            if(!isMove)
            {
                isMove = true;
                timer->stop();
            }
        }
    }
    //if(isScrolling)
        QListView::mouseMoveEvent(e);
}

void ListView::mouseReleaseEvent(QMouseEvent *e)
{
    if(!isMove && itemPress && !isLongPress)
    {
        isClick = true;
    }
        //emit ItemClick(currentItem());

    itemPress = false;
    isPress = false;
    isMove = false;
    timer->stop();

    QListView::mouseReleaseEvent(e);
}

void ListView::stateChanged(QScroller::State newstate)
{
    isScrolling = false;
    if(newstate == QScroller::Scrolling)
    {
        //WELOG_DEBUG() << "Scrolling";
        isScrolling = true;
        timer->stop();
    }
    else if(newstate == QScroller::Dragging)
    {
        //WELOG_DEBUG() << "Dragging";
        timer->stop();
    }
}

void ListView::clicked(const QModelIndex &index)
{
    if(isClick)
    {
        isClick = false;
        ItemClick(index);
    }
}
